package cn.edu.swu.dbcp.auth;

import cn.edu.swu.dbcp.repo.DatabaseService;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");     // 保证与login.html一致
        String password = request.getParameter("pass"); // 保证与login.html一致
        String code = request.getParameter("code");     // 保证与login.html一致

        // 验证码比对
        HttpSession session = request.getSession(true);
        String captcha = (String) session.getAttribute(CaptchaServlet.CAPTCHA_KEY);
        if (captcha == null || !captcha.equalsIgnoreCase(code)) {
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        // 从容器上下文获取数据库访问的服务类
        ServletContext context = this.getServletContext();
        DatabaseService service = (DatabaseService) context.getAttribute(DatabaseService.CONTEXT_KEY);
        // 构建查询SQL
        String template = "select * from user where name='%s' and passwd=md5('%s')";
        // 执行SQL
        try{
            List<user> users = service.query(
                    String.format(template,user,password), new userResultSetVistor()
            );
            // 判断登录逻辑
            if (users.size() > 0) {
                // 需要标记用户有没有登陆，需要建立标记，因而为会话设置标记
                this.loginToken(request,users.get(0));

                response.sendRedirect(request.getContextPath() + "/admin/books");
            } else {
                response.sendRedirect(request.getContextPath() + "/login.html");
            }

        } catch (IOException | SQLException e){
            throw new ServletException(e);
        }
    }

    private void loginToken(HttpServletRequest request, user u){
        HttpSession session = request.getSession(true);
        session.setAttribute(AuFilter.LOGIN_TOKEN_KEY,u);
    }
}
